import type { PluginOption } from 'vite'

import uni from '@dcloudio/vite-plugin-uni'

import UniPolyfill from 'vite-plugin-uni-polyfill'
import vueDevTools from 'vite-plugin-vue-devtools'
import createAutoImport from './auto-import'
import createCompression from './compression'
import createUniHelper from './uni-helper'

import createCisualizer from './visualizer'
import createViteRestart from './vite-restart'

export async function createVitePlugins(viteEnv, isBuild = false) {
  const UnoCSS = (await import('unocss/vite')).default
  const vitePlugins: PluginOption[] = []
  vitePlugins.push(vueDevTools())
  vitePlugins.push(...createUniHelper())
  vitePlugins.push(uni())
  vitePlugins.push(createAutoImport())
  vitePlugins.push(UnoCSS())
  vitePlugins.push(createViteRestart())
  vitePlugins.push(UniPolyfill())

  if (isBuild) {
    vitePlugins.push(...createCompression(viteEnv))
    vitePlugins.push(createCisualizer())
  }

  // 自定义插件禁用vite:vue插件的devToolsEnabled，强制编译 vue 模板时 inline 为 true
  vitePlugins.push({
    name: 'fix-vite-plugin-vue',
    configResolved(config) {
      const plugin = config.plugins.find(p => p.name === 'vite:vue')
      if (plugin && plugin.api && plugin.api.options)
        plugin.api.options.devToolsEnabled = false
    },
  })
  return vitePlugins
}
